#include "games/slidergame.h"

SliderGame::SliderGame(QWidget *parent, int difflvl) :
    BaseGame(parent, difflvl)
{
    // Setup number of sliders and speed of descending (dep on difflvl)
    no_sliders = difficulty_level + 2;
    speed = 3;

    // Timers for sliders descending
    timer = new QTimer(this);
    timer->setInterval(100);
    timer->start();

    // Contains all sliders
    slider_map = new QSlider*[no_sliders];

    // Fill sliders map
    QList<int> list;
    for(int i = 0; i < no_sliders; i++) {
        list << i;
    }

    // Create random permutation for sliders
    rand = QList<int>();
    for(int i = 0; i < no_sliders; i++) {
        QSlider * s = new QSlider(this);
        slider_map[i] = s;
        lay->addWidget(s,0,i);

        rand << list.takeAt(qrand() % (no_sliders - i));
    }

    // Connections
    connect(timer,SIGNAL(timeout()), this, SLOT(onTimeout()));
}

bool SliderGame::isSolved()
{
    // If all sliders have value 100 true else false
    for(int i = 0; i < no_sliders; i++) {
        if( slider_map[i]->value() < 99 ) return false;
    }
    return true;
}

void SliderGame::onTimeout()
{
    // Each timeout descend slider of speed, if corresponding slider is less that 50% high
    for(int i = 0; i < no_sliders; i++) {
        if( slider_map[i]->value() < 50 ) {
            int new_value = slider_map[rand[i]]->value() - speed;
            slider_map[rand[i]]->setValue(new_value);
        }
    }
}
